﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InductBase;

namespace SharpBolt.Sound
{
    public class SfxPlayer: ISoundInstance
    {
        RandomList<SoundSource> Sources;
        List<SoundPlayer> Instances;

        public SfxPlayer()
        {
            Sources = new RandomList<SoundSource>();
            Instances = new List<SoundPlayer>();
            Volume = .25;
        }

        public void Continue()
        {
            Instances.ForEach(p => p.Continue());
        }

        double pan;
        public double Pan
        {
            get
            {
                return pan;
            }
            set
            {
                pan = value;
            }
        }

        double volume;
        public double Volume
        {
            get
            {
                return volume;
            }
            set
            {
                volume = value;
            }
        }

        public void Pause()
        {
            Instances.ForEach(p => p.Pause());
        }

        public void Play(bool loop = false)
        {
            if (Sources.Count < 1) return;
            SoundSource source = Sources.GetRandomItem();
            SoundPlayer sound = Instances.Find(p => p.IsStopped() && p.Source() == source);
            if (sound == null)
            {
                sound = source.GetInstance();
                Instances.Add(sound);
            }
                       
            sound.Volume = volume;
            sound.Pan = pan;
            sound.Play();
        }

        public void Stop()
        {
            Instances.ForEach(p => p.Pause());            
        }

        public void LoadSoundEffect(string fileName)
        {
            if (Sources.Find(p => p.name == fileName) == null)
            {
                Sources.Add(SoundSource.LoadSoundSource(fileName));
            }
        }

        public void LoadSoundEffectList(string listName)
        {
            string text = Engine.Miscs.LoadText(listName);
            var lines = text.Split('\n');
            foreach (var line in lines)
            {
                if (line.Trim().Length == 0) continue;
                LoadSoundEffect(line);
            }
        }
    }
}
